// Copyright (c) 2017 PlanGrid, Inc.

import React, { Component } from 'react';

import '../styles/video.scss';
import Loading from '../loading';

class MyPhotoViewer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      imgWidth: 0,
      imgHeight: 0,
      imageDimensions: {},
    };
  }

  getImageDimensions = (originalWidth, originalHeight) => {
    // Scale image to fit into viewer
    let imgWidth, imgHeight;
    const { height: viewerHeight, width: viewerWidth } = this.props;

    if (originalHeight <= viewerHeight && originalWidth <= viewerWidth) {
      imgWidth = originalWidth;
      imgHeight = originalHeight;
    } else {
      const heightRatio = viewerHeight / originalHeight;
      const widthRatio = viewerWidth / originalWidth;
      if (heightRatio < widthRatio) {
        imgHeight = originalHeight * heightRatio;
        imgWidth = originalWidth * heightRatio;
      } else {
        imgHeight = originalHeight * widthRatio;
        imgWidth = originalWidth * widthRatio;
      }
    }

    return { height: imgHeight, width: imgWidth };
  };
  _onLoad = e => {
    //console.log('target', e.target.offsetHeight, e.target.offsetWidth);
    let originalHeight = e.target.offsetHeight;
    let originalWidth = e.target.offsetWidth;
    const imageDimensions = this.getImageDimensions(originalWidth, originalHeight);
    this.setState({ imageDimensions, loading: false });
  };

  onCanPlay() {
    this.setState({ loading: false });
  }

  renderLoading() {
    if (this.state.loading) {
      return <Loading />;
    }
  }

  render() {
    const containerStyles = {
      width: `${this.state.imageDimensions.width}px`,
      height: `${this.state.imageDimensions.height}px`,
      visibility: this.state.loading ? 'hidden' : 'visible',
    };
    return (
      <div className="pg-driver-view">
        <div className="video-container">
          <img alt="" src={this.props.filePath} style={containerStyles} onLoad={this._onLoad} />
        </div>
      </div>
    );
  }
}

export default MyPhotoViewer;
